package cn.ac.iie.di.ban.data.exchange.runner.slave.task.runTask;


import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.StatusEnum;
import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.task.order.TaskOrderRequest;
import cn.ac.iie.di.ban.data.exchange.runner.commons.protocol.task.order.TaskOrderResponse;
import cn.ac.iie.di.ban.data.exchange.runner.slave.task.checkTask.CheckSQLAndPermissionTask;
import cn.iie.jsqlparser.helper.JSQLParserHelper;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;

/**
 * Created by Black-Laptop on 12/9/2017.
 */
public class QueryTask {
    private String errorMsg;
    private QueryTaskThread queryTaskThread;

    private String uniq_key;
    private String dbHosts;
    private String dbUser;
    private String dbPassword;
    private String dbName;

    //    private String hdfsPath;
    private String ftpIp;
    private int ftpPort;
    private String ftpUser;
    private String ftpPassword;

    private JSQLParserHelper jsqlParserHelper;

    private TaskOrderRequest taskOrderRequest;

    public QueryTask(TaskOrderRequest taskOrderRequest, String dbHosts, String dbUser, String dbPassword, String dbName) throws Exception {
        this.dbHosts = dbHosts;
        this.dbUser = dbUser;
        this.dbPassword = dbPassword;
        this.dbName = dbName;
        this.uniq_key = taskOrderRequest.getUniq_key();
        this.errorMsg = "";
        this.taskOrderRequest = taskOrderRequest;

        init(taskOrderRequest);
    }
//    public QueryTask(TaskOrderRequest taskOrderRequest,String dbHosts , String dbUser , String dbPassword , String dbName,String ftpIp,int ftpPort,String ftpUser, String ftpPassword) throws Exception {
//        this.dbHosts = dbHosts;
//        this.dbUser = dbUser;
//        this.dbPassword = dbPassword;
//        this.dbName = dbName;
//        this.ftpIp = ftpIp;
//        this.ftpPort = ftpPort;
//        this.ftpUser = ftpUser;
//        this.ftpPassword = ftpPassword;
//        this.uniq_key = taskOrderRequest.getUniq_key();
//        this.errorMsg = "";
////        this.resultPath = taskOrderRequest.getResult_path();
//        
//        this.taskOrderRequest = taskOrderRequest;
//        init(taskOrderRequest);
//    }

    private void init(TaskOrderRequest taskOrderRequest) throws Exception {
        CheckSQLAndPermissionTask checkSQLAndPermissionTask = new CheckSQLAndPermissionTask(taskOrderRequest);
        TaskOrderResponse taskOrderResponse = checkSQLAndPermissionTask.checkSQLAndPermission(taskOrderRequest.getUniq_key());


        if (taskOrderResponse.getStatus() != StatusEnum.CHECK_SUCCESS) {
            throw new Exception("checkPermission error:" + taskOrderResponse.getDetail());
        }

        String sql = taskOrderResponse.getDetail();

        try {
            this.jsqlParserHelper = new JSQLParserHelper(sql);
        } catch (Exception e) {
            throw new Exception("sql error:" + sql);
        }
        setSql();
    }

    /**
     * 将channel.table转换成table
     *
     * @throws Exception
     */
    private void setSql() throws Exception {
        List<String> fromList = jsqlParserHelper.getSQLTables();
        List<String> fromListAfter = new ArrayList<String>();
        for (int i = 0; i < fromList.size(); i++) {
            String[] froms = fromList.get(i).split("\\.");
            fromListAfter.add(froms[froms.length - 1]);
        }
        jsqlParserHelper.setSQLTables(fromListAfter);
    }

    public TaskOrderResponse doQueryTask() {
        TaskOrderResponse taskOrderResponse;
        Boolean queryTaskRunSuccess = queryTask();

        if (queryTaskRunSuccess) {
            taskOrderResponse = setDoQueryTaskSuccess();
        } else {
            taskOrderResponse = setDoQueryTaskFail();
        }
        taskOrderResponse.setDetail("");

        return taskOrderResponse;
    }

    private TaskOrderResponse setDoQueryTaskSuccess() {

        TaskOrderResponse taskOrderResponse = new TaskOrderResponse(uniq_key, StatusEnum.QUERY_TASK_SUCCESS, "");
        return taskOrderResponse;
    }

    private TaskOrderResponse setDoQueryTaskFail() {

        TaskOrderResponse taskOrderResponse = new TaskOrderResponse(uniq_key, StatusEnum.QUERY_TASK_ERROR, errorMsg);
        return taskOrderResponse;
    }

    private Boolean queryTask() {
        try {
            queryTaskThread = new QueryTaskThread(taskOrderRequest, jsqlParserHelper, dbHosts, dbUser, dbPassword, dbName);

            queryTaskThread.start();
        } catch (Exception e) {
            errorMsg = ExceptionUtils.getFullStackTrace(e);
            return false;
        }

        return true;
    }

    public Boolean getQueryTaskThreadStatus() {
        return queryTaskThread.isAlive();
    }

    public void stopQueryTaskThread() {
        this.queryTaskThread.stopThrad();
        while (true) {
            if (!queryTaskThread.isAlive()) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
